package callnumber.gtdev5.com.photoVault.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.gtdev5.geetolsdk.mylibrary.callback.BaseCallback;
import com.gtdev5.geetolsdk.mylibrary.http.HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.PermissionUtils;
import com.gtdev5.geetolsdk.mylibrary.util.SpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.Utils;

import org.litepal.crud.DataSupport;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import callnumber.gtdev5.com.photoVault.R;
import callnumber.gtdev5.com.photoVault.base.BaseActivity;
import callnumber.gtdev5.com.photoVault.base.FristBaseActivity;
import callnumber.gtdev5.com.photoVault.bean.Ads;
import callnumber.gtdev5.com.photoVault.bean.Contract;
import callnumber.gtdev5.com.photoVault.bean.Gds;
import callnumber.gtdev5.com.photoVault.bean.ResultBean;
import callnumber.gtdev5.com.photoVault.bean.Swt;
import callnumber.gtdev5.com.photoVault.bean.UpdateBean;
import callnumber.gtdev5.com.photoVault.bean.Vip;
import callnumber.gtdev5.com.photoVault.constants.AppConstans;
import callnumber.gtdev5.com.photoVault.utils.GlideLoadUtils;
import callnumber.gtdev5.com.photoVault.widget.CenterDialog;
import callnumber.gtdev5.com.photoVault.widget.OnDialogClickListener;
import okhttp3.Request;
import okhttp3.Response;

public class SplashActiviy extends FristBaseActivity {
    @BindView(R.id.splash_img)
    ImageView splashImg;
    @BindView(R.id.splash_btn)
    Button splashBtn;
    private boolean isReg; //是否注册
    private Handler mHander = new Handler();
    private int RESULT_ACTION_USAGE_ACCESS_SETTINGS = 1;
    @Override
    protected int getLayouId() {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_splash_activiy;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        isReg = SpUtils.getInstance().getBoolean( AppConstans.LOCK_IS_REG, true );//是否是第一次注册
    }

    @Override
    protected void initDatas() {
        if (Utils.isNetworkAvailable( SplashActiviy.this )) { //如果有网请求权限
            PermissionUtils.checkAndRequestPermission( SplashActiviy.this, Manifest.permission.READ_PHONE_STATE, 1, new PermissionUtils.PermissionRequestSuccessCallBack() {
                @Override
                public void onHasPermission() {
                    regDevice();
                    SpUtils.getInstance().putBoolean(AppConstans.HASSIMKPERMISSON,true);
                }
            } );
        } else {
            mHander.postDelayed( () -> {
                //MainActivity
                openActivity( MainActivity.class );
                finish();
            }, 3000 );
            overridePendingTransition( android.R.anim.fade_in, android.R.anim.fade_out );
        }
    }

    @Override
    protected void initAction() {
        splashBtn.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isNetworkAvailable( SplashActiviy.this )) {
                    getUpdate();
                } else {
                    openActivity( MainActivity.class );
                    finish();
                }
            }
        } );
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        // TODO: add setContentView(...) invocation
        ButterKnife.bind( this );
    }

    /**
     * 注册设备
     */
    private void regDevice() {
        if (isReg) {
            Log.e( "TAG", "开始注册" );
            HttpUtils.getInstance().postRegister(new BaseCallback<ResultBean>() {
                @Override
                public void onRequestBefore() {

                }
                @Override
                public void onFailure(Request request, Exception e) {
                    Log.e( "TAG", "注册失败" );
                    SpUtils.getInstance().putBoolean( AppConstans.LOCK_IS_REG, true );
                }

                @Override
                public void onSuccess(Response response, ResultBean resultBean) {
                    SpUtils.getInstance().putBoolean( AppConstans.LOCK_IS_REG, false );
                    Log.e( "TAG", "注册成功！" + resultBean.isIssucc() );
                    if (resultBean.isIssucc()) {
                        getUpdate();
                    }

                }


                @Override
                public void onError(Response response, int errorCode, Exception e) {
                    Log.e( "TAG", "注册失败" + e.toString() );
                }
            } );

        } else {
            getUpdate();

        }
    }
    private void getUpdate() {
        HttpUtils.getInstance().postUpdate( new BaseCallback<UpdateBean>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {

            }

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onSuccess(Response response, UpdateBean o) {
                /**
                 *      把所有数据全部存入本地数据库
                 */
                if (o != null && response.isSuccessful()) {
                    if (DataSupport.findFirst( UpdateBean.class ) != null) {
                        DataSupport.deleteAll( UpdateBean.class );
                    }
                    o.save();
                    List<Ads> ads = o.getAds();
                    if (DataSupport.findAll( Ads.class ).size() > 0 && DataSupport.findAll( Ads.class ) != null) {
                        DataSupport.deleteAll( Ads.class );
                    }
                    if (ads != null)
                        for (int i = 0; i < ads.size(); i++) {
                            Ads ads1 = ads.get( i );
                               if (ads1.getPos().equals( "1660"
                                 )) {
                                //ImageLoader.getInstance().loadImage( SplashActiviy.this, splashImg, ads1.getImg(), 0, 0, true );
                                GlideLoadUtils.getInstance().glideLoad(SplashActiviy.this,ads1.getImg(),splashImg,R.mipmap.splash_img);
                                splashImg.setOnClickListener( v -> openActionView( ads1.getLink() ) );
                            }
                            ads1.save();
                        }


                    List<Gds> gds = o.getGds();
                    if (DataSupport.findAll( Gds.class ).size() > 0 && DataSupport.findAll( Gds.class ) != null) {
                        DataSupport.deleteAll( Gds.class );
                    }
                    for (int i = 0; i < gds.size(); i++) {
                        Gds gds1 = gds.get( i );
                        if (i == 0) {
                            gds1.setSelect( true );
                        } else {
                            gds1.setSelect( false );
                        }
                        gds1.save();
                    }

                    List<Swt> swt = o.getSwt();
                    if (DataSupport.findAll( Swt.class ).size() > 0 && DataSupport.findAll( Swt.class ) != null) {
                        DataSupport.deleteAll( Swt.class );
                    }
                    for (int i = 0; i < swt.size(); i++) {
                        Swt swt1 = swt.get( i );
                        swt1.save();
                    }

                    Contract contract = o.getContract();
                    if (DataSupport.findFirst( Contract.class ) != null) {
                        DataSupport.deleteAll( Contract.class );
                    }
                    contract.save();

                    Vip vip = o.getVip();
                    if (DataSupport.findFirst( Vip.class ) != null) {
                        DataSupport.deleteAll( Vip.class );
                    }
                    vip.save();

                }

                mHander.postDelayed( () -> {
                    openActivity( MainActivity.class );
                    finish();
                }, 3000 );

                overridePendingTransition( android.R.anim.fade_in, android.R.anim.fade_out );


            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        } );
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult( requestCode, permissions, grantResults );
        if (requestCode == RESULT_ACTION_USAGE_ACCESS_SETTINGS)
            PermissionUtils.onRequestPermissionResult( SplashActiviy.this, Manifest.permission.READ_PHONE_STATE, grantResults, new PermissionUtils.PermissionCheckCallBack() {
                @Override
                public void onHasPermission() {
                    regDevice();
                    if (!isReg){
                        Intent intent = new Intent( SplashActiviy.this, MainActivity.class );
                        startActivity( intent );
                        finish();
                        overridePendingTransition( android.R.anim.fade_in, android.R.anim.fade_out );
                    }
                    SpUtils.getInstance().putBoolean(AppConstans.HASSIMKPERMISSON,true);
                }

                @Override
                public void onUserHasAlreadyTurnedDown(String... permission) {
                    ShowTipDialog("温馨提示",
                            "授予权限能使数据绑定手机哦，点击确定继续授权",
                            "确定", new OnDialogClickListener() {
                                @Override
                                public void OnDialogOK() {
                                    PermissionUtils.requestPermission(SplashActiviy.this,
                                            Manifest.permission.READ_PHONE_STATE,
                                            1);
                                }

                                @Override
                                public void OnDialogExit() {
                                   regDevice();
                                }
                            });
                }

                @Override
                public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                    regDevice();
                }
            } );
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHander != null) {
            mHander.removeCallbacksAndMessages( null );
        }
    }
    public void ShowTipDialog(String name, String tipcontent, String buttonoktext, OnDialogClickListener listener) {
        int[] intids = new int[]{
                R.id.dialog_bt_dis,
                R.id.dialog_bt_ok
        };
        CenterDialog dialog = new CenterDialog(SplashActiviy.this, R.layout.dialog_tip_2_bt_layout, intids);
        dialog.setOnCenterClickListener((dial, view) -> {
            if (view.getId() == R.id.dialog_bt_ok) {
                listener.OnDialogOK();
                dialog.dismiss();
            }
            if (view.getId() == R.id.dialog_bt_dis) {
                dialog.dismiss();
                listener.OnDialogExit();
            }
        });
        dialog.show();
        dialog.setText(R.id.dialog_tv_title, name);
        dialog.setText(R.id.dialog_tv_text, tipcontent);
        dialog.setText(R.id.dialog_bt_ok, buttonoktext);
    }
}
